<!--
  * 支付订单流水
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-col :span="6">
        <a-form-item label="订单号" class="smart-query-form-item">
          <a-select
            style="width: 30%"
            v-model:value="queryForm.orderField"
            :options="ORDER_FIELD"
            :dropdown-match-select-width="false"
            placeholder="请选择"
          />
          <a-input style="width: 70%" v-model:value="queryForm[queryForm.orderField]" placeholder="订单号" />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="支付通道" class="smart-query-form-item">
          <CustomSelect
            v-model:value="queryForm.channelId"
            :placeholder="'请选择支付通道'"
            :api="channelApi.queryPage"
            value-field="id"
            label-field="channelName"
          />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="分账状态" class="smart-query-form-item">
          <a-select v-model:value="queryForm.allocStatus" :options="ALLOC_STATUS" :dropdown-match-select-width="false" placeholder="请选择" />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="交易状态" class="smart-query-form-item">
          <a-select v-model:value="queryForm.status" :options="TRADE_STATUS" :dropdown-match-select-width="false" placeholder="请选择" />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="交易日期" class="smart-query-form-item">
          <a-range-picker :allowClear="false" class="w-full" :inputReadOnly="true" v-model:value="queryForm.cTime" @change="onChangeTime" />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="门店名称" class="smart-query-form-item">
          <CustomSelect
            v-model:value="queryForm.storeId"
            :placeholder="'请选择'"
            :api="storeApi.page"
            queryParamKey="storeNameLeftLike"
            valueField="id"
            labelField="storeName"
          />
        </a-form-item>
      </a-col>
      <!-- <a-col :span="6">
        <a-form-item label="交易订单号" class="smart-query-form-item">
          <a-input v-model:value="queryForm.id" placeholder="请输入聚合平台订单号" /> </a-form-item
      ></a-col> -->
      <!-- <a-col :span="6">
        <a-form-item label="商户名称" class="smart-query-form-item">
          <CustomSelect
            v-model:value="queryForm.merchantId"
            :placeholder="'请选择'"
            :api="merchantApi.page"
            :queryParams="merchantParams"
            queryParamKey="companyNameLeftLike"
            valueField="id"
            labelField="companyName"
          />
        </a-form-item>
      </a-col> -->
      <!-- <a-col :span="6">
        <a-form-item label="所属代理商" class="smart-query-form-item">
          <CustomSelect
            v-model:value="queryForm.agentId"
            :placeholder="'请选择所属代理'"
            :api="agentApi.page"
            queryParamKey="companyNameLeftLike"
            value-field="id"
            label-field="companyName"
          />
        </a-form-item>
      </a-col> -->
      <a-col :span="6">
        <a-form-item class="smart-query-form-item">
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery" class="smart-margin-left10">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-form-item></a-col
      >
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 统计 ----------->
    <a-row>
      <a-col :span="24">
        <div class="w-full flex justify-end">
          <a-button type="primary" @click="showOverview = !showOverview">{{ showOverview ? '关闭统计' : '数据统计' }} </a-button>
        </div>
      </a-col>
      <a-col :span="24" v-if="showOverview">
        <div class="flex justify-around p-y-3">
          <div v-for="(item, key, i) in overviewMap" :key="key" class="text-white w-80 p-x-3">
            <div
              class="overview-box flex flex-col items-center justify-center rounded-lg w-full p-y-3"
              :style="{
                backgroundColor: BOX_COLORS[i],
              }"
            >
              <div>
                <span>￥</span>
                <span style="font-size: 30px" class="font-bold">{{ formatToMoney(overviewData[key] / 100) }}</span>
              </div>
              <div>
                {{ item }}
              </div>
            </div>
          </div>
        </div>
      </a-col>
    </a-row>
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-title">数据列表</div>
      <div class="smart-table-setting-block">
        <!-- <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.OPERATION.MERCHANT_DAY_ORDER" :refresh="queryData" /> -->
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table
      size="small"
      :dataSource="tableData"
      :columns="columns"
      rowKey="id"
      bordered
      :loading="tableLoading"
      :pagination="false"
      :scroll="{ x: 'max-content' }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="refundForm(record)" type="link" v-if="record.tradeAmt != record.refundAmt">退款</a-button>
            <a-button @click="viewForm(record)" type="link">详情</a-button>
            <a-button @click="viewList(record)" type="link" v-if="record.allocStatus == '1' || record.allocStatus == '2'">分账明细</a-button>
            <a-button @click="goTo('/refund/list', record)" type="link" v-if="record.refundAmt > 0">退款流水</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>
  </a-card>
  <TradeFlowDetail v-model:open="detailOption.open" :row-data="detailOption.rowData" />
  <AllocOrderList v-model:open="allocOrderListOption.open" :row-data="allocOrderListOption.rowData" />
  <RefundModal ref="formRef" @success="queryData" />
</template>
<script setup>
  import { reactive, ref, onMounted, getCurrentInstance, watch, h } from 'vue'
  import { orderApi } from '/@/api/business/b-merchant/order/order-api'
  import { channelApi } from '/@/api/business/b-merchant/channel/channel-api'
  import { merchantApi } from '/@/api/business/b-merchant/merchant/merchant-api.js'
  import { storeApi } from '/@/api/business/b-merchant/store/store-api'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import TableOperator from '/@/components/support/table-operator/index.vue'
  import TradeFlowDetail from '/@/components/business/comment/tradeFlow/tradeFlowDetail.vue'
  import AllocOrderList from '/@/components/business/comment/alloc-order/alloc-order-list.vue'
  import RefundModal from '/@/components/business/comment/refund/refund-modal.vue'
  import { TABLE_ID_CONST } from '/@/constants/support/table-id-const.js'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { message, Tag } from 'ant-design-vue'
  import dayjs from 'dayjs'
  import { formatToMoney, selectDictLabel } from '/@/utils/common'
  import {
    ORDER_FIELD, //订单号对应字段
    ALLOC_STATUS, //分账状态
    TRADE_STATUS, //交易状态
    REFUND_STATEMENT_STATUS,
    ZZB_PAY_WAY,
  } from '/@/constants/dict'
  import { useRouter } from 'vue-router'
  /* 路由跳转 */
  const router = useRouter()

  const { proxy } = getCurrentInstance()
  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '订单号',
      dataIndex: 'refundOrder',
      width: 300,
      customRender: (column) => {
        let { id, oId, tId } = column.record
        let mText = id ? h('div', { style: { paddingBottom: '10px' } }, [h(Tag, { color: '#2db7f5' }, '交易'), id]) : ''
        let oText = oId ? h('div', { style: { paddingBottom: '10px' } }, [h(Tag, { color: 'orange' }, '支付'), oId]) : ''
        let tText = tId ? h('div', [h(Tag, { color: 'cyan' }, '渠道'), tId]) : ''

        return h('div', [mText, oText, tText])
      },
      ellipsis: true,
    },
    {
      title: '交易时间',
      dataIndex: 'cTime',
      customRender: (column) => dayjs(column.text).format('YYYY-MM-DD HH:mm:ss'),
      width: 180,
      ellipsis: true,
    },
    {
      title: '门店名称',
      dataIndex: 'storeName',
      ellipsis: true,
    },
    {
      title: '收银员',
      dataIndex: 'storeStaffName',
      ellipsis: true,
    },
    {
      title: '分账状态',
      dataIndex: 'allocStatus',
      customRender: (column) => selectDictLabel(ALLOC_STATUS, column.text),
      ellipsis: true,
    },
    {
      title: '订单金额',
      dataIndex: 'tradeAmt',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '退款金额',
      dataIndex: 'refundAmt',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '实际分账金额',
      dataIndex: 'allocAmt',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '预估交易手续费',
      dataIndex: 'estimatedFee',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '实际手续费',
      dataIndex: 'fee',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '营收金额',
      dataIndex: 'revenueAmt',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '结算金额',
      dataIndex: 'settleAmt',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '实收金额',
      dataIndex: 'paidUpAmt',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '支付通道',
      dataIndex: 'channelName',
      ellipsis: true,
    },
    {
      title: '交易类型',
      dataIndex: 'payType',
      customRender: (column) => proxy.$smartEnumPlugin.getDescByValue('ZZB_PAY_TYPE_ENUM', column.text),
      ellipsis: true,
    },
    {
      title: '支付方式',
      dataIndex: 'payWay',
      customRender: ({ text }) => selectDictLabel(ZZB_PAY_WAY, text),
      ellipsis: true,
    },
    {
      title: '商家账户/商户号',
      dataIndex: 'channelMchid',
      ellipsis: true,
    },
    {
      title: '交易状态',
      dataIndex: 'status',
      customRender: (column) => selectDictLabel(TRADE_STATUS, column.text),
      ellipsis: true,
    },
    // {
    //   title: '交易报错原因',
    //   dataIndex: 'channelError',
    //   ellipsis: true,
    // },
    {
      title: '操作',
      dataIndex: 'action',
      ellipsis: true,
      fixed: 'right',
    },
  ])

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    orderField: 'keyWord',
    keyWord: undefined, //全部
    mId: undefined, //交易订单号（系统生成的订单号）
    oId: undefined, //支付订单号（支付宝/微信返回的订单号）
    tId: undefined, //渠道订单号（间连返回的订单编号）
    cTime: [dayjs().startOf('days'), dayjs().endOf('days')],
    cTimeBegin: dayjs().startOf('day').valueOf(), //前一天
    cTimeEnd: dayjs().endOf('day').valueOf(), //前一天
    id: undefined, //交易订单号
    merchantId: undefined, //商户名称
    storeId: undefined, //门店id
    channelId: undefined, //支付通道
    allocStatus: undefined,
    status: undefined,
    refundStatementStatus: undefined,
    agentId: undefined,
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      const payload = { ...queryForm }
      delete payload.cTime
      let queryResult = await orderApi.page(payload)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } /* finally {
    } */
    queryOverview()
    tableLoading.value = false
  }

  // 查询统计数据
  const showOverview = ref(true)
  const BOX_COLORS = ['#4786E5', '#4786E5', '#2C9E96', '#B650DA', '#F16527']
  const overviewMap = {
    tradeAmt: '交易金额',
    revenueAmt: '营收金额',
    paidUpAmt: '实收金额',
    refundAmt: '退款金额',
    settleAmt: '结算金额',
  }
  const overviewData = ref({})
  async function queryOverview() {
    try {
      const payload = { ...queryForm }
      let queryResult = await orderApi.getOverview(payload)
      overviewData.value = queryResult.data
      console.log('queryResult===>', overviewData.value)
    } catch (e) {
      smartSentry.captureError(e)
    } /* finally {
    } */
  }

  function onChangeTime(data) {
    queryForm.cTimeBegin = data[0].startOf('days').valueOf()
    queryForm.cTimeEnd = data[1].endOf('days').valueOf()
  }

  // 详情
  const detailOption = ref({
    open: false,
    rowData: {},
  })
  const viewForm = (row) => {
    detailOption.value = {
      open: true,
      rowData: row,
    }
  }
  // 分账明细
  const allocOrderListOption = ref({
    open: false,
    rowData: {},
  })
  const viewList = (row) => {
    allocOrderListOption.value = {
      open: true,
      rowData: row,
    }
  }
  function goTo(url, data) {
    let { id } = data
    router.push({ path: url, query: { id } })
  }
  // ---------------------------- 退款 ----------------------------
  const formRef = ref()

  function refundForm(data) {
    formRef.value.show({ ...data, orderId: data.id })
  }

  // 切换订单号选择
  watch(
    () => queryForm.orderField,
    (val, oldVal) => {
      if (val) {
        queryForm[oldVal] = undefined
      }
    },
  )
  onMounted(queryData)
</script>
